/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mytdev.commons.action;

import java.util.Arrays;
import java.beans.ExceptionListener;
import java.util.Iterator;
import static com.mytdev.commons.action.Action.Result.SUCCESS;
import static com.mytdev.commons.action.Action.Result.FAILURE;

/**
 * An action which is a sequence of actions. Performing this action results in 
 * trying to perform all the sequence actions.
 * If an action of the sequence fails, this action stop and return FAILURE result.
 * 
 * @author Yann D'Isanto
 */
public class ActionSequence extends AbstractAction implements ExceptionListener {

    private Iterable<Action> actionsProvider;

    /**
     * Creates an ActionSequence using the specified actions.
     * @param actions 
     */
    public ActionSequence(Action[] actions) {
        this(Arrays.asList(actions));
    }

    /**
     * Creates an ActionSequence that uses the specified iterable to retreive the actions.
     * @param actionsProvider an Iterable
     */
    public ActionSequence(Iterable<Action> actionsProvider) {
        this.actionsProvider = actionsProvider;
    }

    @Override
    public Result perform() {
        Iterator<Action> it = actionsProvider.iterator();
        it.hasNext();
        for(Iterator<Action> actions = actionsProvider.iterator(); actions.hasNext();) {
            Action action = actions.next();
            action.addExceptionListener(this);
            action.run();
            action.removeExceptionListener(this);
            Result result = action.getResult();
            if (FAILURE.equals(result)) {
                return FAILURE;
            }
        }
        return SUCCESS;
    }

    @Override
    public void exceptionThrown(Exception e) {
        fireExceptionThrown(e);
    }
}
